<?php

use \GatewayWorker\Lib\Gateway;
use GatewayWorker\Lib\Context;
class GroupMgr
{
    function GroupMgr(){
        require_once __DIR__ . '/../GlobalData/src/Client.php';
        // 连接Global Data服务端
        $this->_global_data = new GlobalData\Client('127.0.0.1:2207');
        $this->test();
        // 触发$global->__isset('somedata')查询服务端是否存储了key为somedata的值
        //isset($global->somedata);

        // 触发$global->__set('somedata',array(1,2,3))，通知服务端存储somedata对应的值为array(1,2,3)
        //$global->somedata = array(1,2,3);

        // 触发$global->__get('somedata')，从服务端查询somedata对应的值
        //var_export($global->somedata);

        // 触发$global->__unset('somedata'),通知服务端删掉somedata及对应的值
        //unset($global->somedata);
    }
    private $_global_data;// GlobalData\Client

    //测试GlobalData功能
    public function test(){
        echo "测试GlobalData功能 赋值=1\n";
        $this->_global_data->somedata  = 1;
        echo "测试GlobalData功能 读取={$this->_global_data->somedata}\n";
    }

    public function getSplMemberInfos($group_id){
        $ret = $this->_global_data->__get("somedata$group_id");
        if(!isset($ret))
            $ret = array();
        return $ret;
    }

    public function getSplMemberInfoCount($group_id){
        $infos = $this->getSplMemberInfos($group_id);
        $count = count($infos);
        return $count;
    }

    public function setSplMemberInfos($group_id, $splmember_info){
        return $this->_global_data->__set("somedata$group_id", $splmember_info);
    }

    public function clearSplMemberInfos($group_id){
        return $this->_global_data->__unset("somedata$group_id");
    }

    //true 写成功
    //false 写失败
    public function writeMemberInfo(member_info $member_info, $group_id){
        $member_info->card_type = CardType::Invalid;//未发牌
        $member_info->support_type = SupportType::Invalid;//未发牌

        //跨服数据
		$splmember_infos = $this->getSplMemberInfos($group_id);

		//跨服数据读取
		$splmember_info = $splmember_infos[$member_info->uid];
		if(isset($splmember_info)){
			if(isset($splmember_info->card_type)){
				$member_info->card_type = $splmember_info->card_type;
			}
			if(isset($splmember_info->support_type)){
				$member_info->support_type = $splmember_info->support_type;
			}
            return true;
		}else{
            return false;
        }
    }

    public function storeSlpMemberInfo($uid, $group_id, $card_type, $support_type){
        $splmember_infos = $this->getSplMemberInfos($group_id);
		$splmember_info = $splmember_infos[$uid];
		if(!isset($splmember_info)){
            $splmember_info = new splmember_info();
            $splmember_info->uid = $uid;
        }
        if(isset($card_type))
            $splmember_info->card_type = $card_type;
        else
            echo "不设置卡牌类型\n";
        if(isset($support_type))
            $splmember_info->support_type = $support_type;
        $splmember_infos[$uid] = $splmember_info;
        $this->setSplMemberInfos($group_id, $splmember_infos);
    }

    //#error 不能跨服
	private $_group_match_index = 0;
	public function getActiveGroupId(string $group_id){
        if(!isset($group_id) || $group_id == ""){
            return;
        }

		//这个组的人，全部下线了
		$client_id_count = Gateway::getClientCountByGroup($group_id);
		if($client_id_count < 1 || $client_id_count > cmd_createroom::$MaxNum - 1){
			return;
		}

        // $client_id_list = Gateway::getClientIdListByGroup($group_id);
        // foreach ($client_id_list as $client_id) {
        //     if($client_id == $active_client_id)
        //         return $group_id;
        // }

		//todo : 询问玩家是否重新进房间
		return $group_id;
	}


    public function joinGroup($group)
    {
        $client_id = Context::$client_id;
        //设置
        $_SESSION[SessionTag::group_id] = $group;
        Gateway::joinGroup($client_id, $group);
    }

    private function leaveGroupInternal($group_id){
        //$group_id = $this->getGroupId($client_id);
        $ret = true;
       if(!isset($group_id)){
       		echo "can not find group_id, when leave group\n";//,client_id=$client_id\n";
       		$ret = false;
       }else{
            //清除
            unset($_SESSION[SessionTag::group_id]);
       }

        $num = Gateway::getClientCountByGroup($group_id);
        if($num < 1){
            echo "清除房间缓存数据 num=$num, group_id=$group_id\n";
            //清除正在战斗的房间
            //unset($_groupid_2_personwrap[$group_id]);
            $this->clearSplMemberInfos($group_id);
        }

        return $ret;
    }

    public function leaveGroup()
    {
        $group_id = $this->getGroupId();
        $client_id = Context::$client_id;
        if(isset($group_id)){
            Gateway::leaveGroup($client_id, $group_id);

            //广播
            $notify_exitroom = new notify_exitroom();
            $user_id = Gateway::getUidByClientId($client_id);
            $notify_exitroom->uid = $user_id;
		    Events::sendToGroup($group_id, notify_exitroom::class, $notify_exitroom);
        }

        //公用代码
        return $this->leaveGroupInternal($group_id);
    }


    public function leaveGroupWhenOffline()
    {
        $user_id = $this->getUid();
        $group_id = $this->getGroupId();
        $num = 0;
        if(isset($group_id))
            $num = Gateway::getClientCountByGroup($group_id);

        //公用代码
        if(!$this->leaveGroupInternal($group_id)){
            return;
        }

        //广播
        if($num > 0){
            $notify_memberoffline = new notify_memberoffline();
            $notify_memberoffline->uid = $user_id;
		    Events::sendToGroup($group_id, notify_memberoffline::class, $notify_memberoffline);
        }
    }


    public function getGroupId(){
    	return $_SESSION[SessionTag::group_id];
    }

    public function getUid(){
    	return $_SESSION[SessionTag::uid];
    }

    public function createMatchGroupId(){
    	// $this->_group_match_index++;
        // if($this->_group_match_index > 147483646)
        //     $this->_group_match_index = 1;
    	// return strval($this->_group_match_index);
        //临时逻辑，当有房间玩了超过一天，还没退出。有小概率会重复房号
        $time_str = date('H:i:s', time());
        $time_arry = explode(':', $time_str);
		if(count($time_arry) != 3)
			throw new Exception("{count($time_arry)} != 3");
        //$day  = intval($time_arry[0]);
		$hour  = intval($time_arry[0]);
		$min = intval($time_arry[1]);
		$sec = intval($time_arry[2]);

        $prefix = strval($hour + $min);
        $posfix = strval($sec + rand(0,39));
        $group_id = "$prefix$posfix";
        return $group_id;
    }

    // //=========记录正在战斗的房间 Start=========
    // private $_groupid_2_personwrap = array();
    // public function startBattle($group_id, $person_wrap){//notify_enterbattle
    //     $this->_groupid_2_personwrap[$group_id] = $person_wrap;
    // }
    // public function isBattle($group_id){
    //     $person_wrap = $this->_groupid_2_personwrap[$group_id];
    //     return isset($person_wrap);
    // }
    // //return list
    // public function &getBattlePersonWrap($group_id){
    //     return $this->_groupid_2_personwrap[$group_id];
    // }
    // //=========记录正在战斗的房间 End=========
}